package org.sump.mysql;

import java.util.ArrayList;
import java.util.List;

import org.sump.data.HasChildren;
import org.sump.data.HasParent;
import org.sump.data.Resource;
import org.sump.data.ResourceType;

public class MySQLResource implements Resource, HasChildren, HasParent {

	private String name;
	private List<Resource> children = new ArrayList<Resource>();
	private HasChildren parent;
	private ResourceType resourceType;
	
	public MySQLResource(String name, ResourceType resourceType) {
		this.name = name;
		this.resourceType = resourceType;
	}

	public String getName() {
		return name;
	}

	public List<Resource> getChildren() {
		return children;
	}

	public HasChildren getParent() {
		return parent;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setChildren(List<Resource> children) {
		this.children = children;
		for(Resource child : children) {
			if(child instanceof MySQLResource) {
				MySQLResource dbResource = (MySQLResource) child;
				if(dbResource.getParent() != this) {
					dbResource.setParent(this);
				}
			}
		}
	}

	public void setParent(HasChildren parent) {
		this.parent = parent;
	}

	public ResourceType getResourceType() {
		return resourceType;
	}

	@Override
	public String toString() {
		return name;
	}

	

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((children == null) ? 0 : children.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result
				+ ((resourceType == null) ? 0 : resourceType.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final MySQLResource other = (MySQLResource) obj;
		if (children == null) {
			if (other.children != null)
				return false;
		} else if (!children.equals(other.children))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (resourceType == null) {
			if (other.resourceType != null)
				return false;
		} else if (!resourceType.equals(other.resourceType))
			return false;
		return true;
	}

	public Resource getChild(String name, ResourceType resourceType) {
		for(Resource resource : children) {
			if(resource.getName().equals(name) && resource.getResourceType().equals(resourceType)) {
				return resource;
			}
		}
		return null;
	}
	
	
}